package com.cf.api.task;

import com.cf.api.service.StudyGenService;
import com.md.common.utils.FileUtils;
import com.md.common.utils.date.DateUtil;
import com.md.common.utils.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.time.LocalDate;
import java.util.Map;

//@Component
//@EnableScheduling
public class StudyGenTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(StudyGenTask.class);

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private StudyGenService studyGenService;

    // @Scheduled(cron = "0 0 1 * * ?")
    public void generate() {
        LOGGER.info("--------- g..s.. --------");

        String content = FileUtils.readFileContent("D:/deploy/cf-collect/gen");
        Map map = JSONUtil.jsonToMap(content);
        if (map == null) {
            LOGGER.error("gen read map is null");
            return;
        }
        int p = Integer.parseInt(map.get("p").toString());

        studyGenService.generateStudy(LocalDate.now().minusDays(1), p);
    }

    // @PostConstruct
    public void initGen() {

        threadPoolTaskExecutor.execute(() -> {

            LOGGER.info("--------- g..s.. --------");

            try {
                String content = FileUtils.readFileContent("D:/deploy/cf-collect/init_gen");
                Map map = JSONUtil.jsonToMap(content);
                if (map == null) {
                    LOGGER.error("gen read map is null");
                    return;
                }
                String start = map.get("start").toString();
                int p = Integer.parseInt(map.get("p").toString());

                LocalDate date = DateUtil.parseLocalDate(start);

                while (!date.isAfter(LocalDate.now().minusDays(1))) {
                    studyGenService.generateStudy(date, p);
                    date = date.plusDays(1);
                }
                LOGGER.error("gen date is after now [{}]", date);

                boolean delete = new File("D:/deploy/cf-collect/init_gen").delete();
                LOGGER.error("gened data successfully. delete init_gen [{}]", delete);
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            }

        });

    }

}
